import {
  getImage,
  getPage,
  getTabbar,
  ChatConfig
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  storage,
  promisify,
  $toast,
  $loading,
  $query
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import {
  headerInfo
} from '../../utils/env'
let app = getApp();
let topStyle, leftStyle, tipTopStyle;

{
  let {
    height,
    right,
    menuWidth
  } = headerInfo
  leftStyle = `right: ${((menuWidth / 2) / 2) + right}px`;
  tipTopStyle = `top: ${height}px;`;
  topStyle = `top: ${height + 10}px;`;
}
Page({

  /**
   * 页面的初始数据 
   */
  data: {
    getImage: getImage,
    getPage: getPage,
    logged: 0,
    loading: 0,
    userId: 0,
    navbar: {},
    window: {},
    city: "",
    hfListIndex: 0,
    botZtListIndex: 0,
    timesHours: 0,
    guize: {},
    timesMinute: 0,
    timesSecond: 0,
    goodsNavFix: false,
    goodsNavType: 1,
    goodsList: [],
    goodsListPage: 1,
    goodsListPages: 0,
    loadmore: false,
    loaddone: false,
    rec_list: [],
    rec_pageindex: 0,
    rec_pages: 0,
    rec_loadmore: true,
    rec_loaddone: false,
    popupShow: false,
    popupShow1: false,
    popupShowTip: false,
    showwellcome: false,
    islocation: false,
    abnor: false,
    tipTopStyle: tipTopStyle,
    leftStyle: leftStyle,
    topStyle: topStyle,
    imgheights: {},
    curBannerHeight: 0,
    curshop: 0,
    value1: 0,
    s_province: 0,
    s_city: 0,
    option1: [{
        text: '离我最近',
        value: 0
      },
      {
        text: '智能排序',
        value: 1
      },
      {
        text: '评分从高到低',
        value: 2
      },
    ],
    regionInfo: [],
    province: [],
    cities: [],
    zonelist: [],
    zoneid: 0,
    navbarInitHeight: 0, //导航栏高度
    stkInitHeight: 0, //吸顶盒子高度
    isFixedTop: false, //是否固定顶部
    popupads: [],
    socketOpen: false, // WebSocket连接状态
    socketMsgQueue: [], // WebSocket消息队列
    manualStop: false,
    shop_list: [],
    shop_list_top: [],
    shop_list_bot: [],
    product_list: [],
    discountshoplist: [],
    isbgtop:false
  },

  setToggle(property) {
    this.setData({
      [property]: !this.data[property],
    })
  },

  handleNotouch() {
    return false
  },
  /**
   * 获取地区
   */
  getRegionInfo() {
    return new Promise((resolve) => {
      storage.get('regionInfo').then((res) => {
        this.setData({
          regionInfo: res,
          pickerArea: false
        });
        console.log("getRegionInfo----------", this.data.regionInfo)
        resolve(res);
      }).catch((res) => {
        http.get(api.default, {
          data: {
            action: 'district'
          }
        }, false).then((res) => {
          const {
            data
          } = res.data;
          this.setData({
            regionInfo: data,
            pickerArea: false
          });
          storage.set('regionInfo', data);
          resolve(data);
        });
      });
    });
  },
  imageLoad: function (e) { //获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  updateDot(data) {
    let dots = data.detail.dots;
    this.setData({
      dots
    })
  },
  shopchange: function (e) {
    this.setData({
      curshop: e.detail.current
    })
  },
  handlePopupClose() {
    this.setData({
      popupShow: false
    })
  },
  
  handlePopupClose2() {
    this.setData({
      islocation: false
    })
  },

  handlePopupShare() {
    this.setData({
      popupShow1: true,
      popupShowTip: false,
    })
  },

  handlePopupCloseTip() {
    this.setData({
      popupShow1: false,
    })
  },
  pingtai() {
    this.setData({
      popupShow: true
    })
  },
  gocompanydetail(e) {
    console.log('eee', e)
    const data = e.detail.data || e.currentTarget.dataset;
    console.log('data===================', data)
    if (data.id) {
      wxApi.navigateTo('/pages/companydetail/index', {
        id: data.id,
        distance: data.distance
      });
    }
  },

  goActiveShop() {
    let {
      ID
    } = this.data.activedData;
    wxApi.navigateTo(getPage.activeShop, {
      aid: ID
    });
  },

  goCouponpro() {
    wxApi.navigateTo(getPage.couponProduct);
  },

  // gotest() {

  //   wxApi.navigateTo('/subPackages/pages/yaoqinguser/yaoqinguser', {
  //     shopName: 'xz',
  //     shopid: 2634,
  //     img: api.imageCdn + 'users/m17240605530004882.png'
  //   });

  // },
  gocompanydetailCur(e) {
    const data = e.currentTarget.dataset;
    if (data.id) {
      wxApi.navigateTo('/pages/companydetail/index', {
        id: data.id,
        distance: data.distance
      });
    }
  },
  gocompany() {
    wxApi.switchTab('/pages/company/home');
  },
  /**
   * 密码修改--网络请求
   */
  zoneSubmit(e) {
    var zoneid = this.data.zoneid;
    var cityid = this.data.s_city;
    var provinceid = this.data.s_province;
    const {
      regionInfo
    } = this.data;
    if (zoneid > 0 || cityid > 0 || provinceid > 0) {
      app.globalData.zoneid = zoneid ? zoneid : (cityid ? cityid : provinceid);
      console.log('zoneSubmit==================zoneid=', app.globalData.zoneid);
      //获取设置城市id
      http.post(api.default, {
        data: {
          action: 'getregioninfo',
          id: app.globalData.zoneid
        }
      }, false).then((res) => {
        const {
          data
        } = res.data;
        if (data != null) {
          app.globalData.zone = data;
          if (e != undefined) {
            this.setData({
              islocation: false
            });
          }
          this.setData({
            city: app.globalData.zone.shortname
          });
          this.getProductsInfo((res) => {
            this.setData({
              goodsList: res.list,
              loadmore: false,
            });
            if (this.data.loaddone || res.list.length == 0) {
              this.setData({
                rec_pageindex: 1,
                rec_pages: 0
              });
              this.getRecShopList((res1) => {
                this.setData({
                  rec_list: res1.list,
                  rec_loadmore: false,
                });
              });
            }
          });
          this.getActivedList();
        }
      });
    } else {
      $toast('请选择城市');
    }
  },
  mesClick(e) {
    //wxApi.navigateTo("/pages/location/index");
    this.setData({
      islocation: true
    });
  },
  gochoujiang() {
    wxApi.navigateTo(getPage.choujiang);
  },
  gojiadian() {
    wxApi.navigateTo(getPage.jiadian);
  },
  gojifen(e) {
    const data = e.currentTarget.dataset || e.target.dataset;

    const url = data.url;
    if (url.indexOf('http') > -1)
      wxApi.navigateTo("/pages/web/web?id=" + url);
    else
      wxApi.navigateTo(url);
  },

  /**
   * swiper 记录当前值
   */
  hfListChange(e) {
    this.setData({
      hfListIndex: e.detail.current
    })
  },

  botZtListChange(e) {
    this.setData({
      botZtListIndex: e.detail.current
    })
  },

  /**
   * 搜索
   */
  visitSearch() {
    wxApi.navigateTo(getPage.search);
  },

  gosheji() {
    wxApi.redirectTo('/pages/designer/home');
  },
  gomdhd() {
    console.log(getPage.mdhd)
    wxApi.redirectTo(getPage.mdhd);
  },
  gozhuangxiu() {
    console.log(getPage.customer)
    wxApi.navigateTo(getPage.mfsheji);
    // wxApi.redirectTo(getPage.customer);
  },
  gojiancai() {
    wxApi.redirectTo(getPage.zhucai);
  },
  goBankPage(e){
    let {aid} = e.currentTarget.dataset;
    if(aid==162){
      this.getCoupon()
    }else{
      wxApi.navigateTo(getPage.qzbank);
    }

  },

  // 领取优惠券
  getCoupon(){
    let { userId } = this.data;
    if(userId){
      console.log('coupon===================userId=======',userId)
      http.post(api.default, {
        data: {
          action: 'getplatcoupon',
          userid: userId
        }
      }, true).then(res => {
        console.log('res=================>', res)
        $toast(errmsg,{
          icon: 'fail',
          times: 300,
        });
      }).finally(()=>{
        setTimeout(()=>{
          this.setData({
            popupShow:false
          })
        },300)
      })
    }else{
      wxApi.navigateTo(getPage.login);
    }
  },
  
  golink(e) {
    console.log('eeeeee', e)
    const data = e.currentTarget.dataset || e.target.dataset;
    //转为小写并去除左右空格
    var str = data.url.toLowerCase();
    if (str != "") {
      if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
        wxApi.navigateTo("/pages/web/web?id=" + str);
      } else if (str.indexOf('mm://') == 0) {
        var array = str.split('_');
        if (array[0].replace("mm://", "") == 'shop') {
          wxApi.navigateTo('/pages/companydetail/index', {
            id: array[1]
          });
        }
      } else if (str.indexOf('ym://') == 0) {
        var url = str.replace("ym://", "");
        if(url.indexOf('subpackages')>0){
          url = url.replace("subpackages", "subPackages");
        }
        wxApi.navigateTo(url);
      } else {
        wxApi.navigateTo("/pages/goods/goods?id=" + str);
      }
    }
  },

  // 获取活动数据
  getActivedList() {
    let {
      userId,
      s_city,
      zoneid,
      s_province
    } = this.data;
    var latitude = 0,
      longitude = 0;
    var mylocation = null;
    if (wx.getStorageSync('mylocation') == "" && app.globalData.zone == null) {
      //wxApi.navigateTo("/pages/location/index");
      this.setData({
        islocation: true
      });
      return;
    } else if (wx.getStorageSync('mylocation') != "") {
      mylocation = JSON.parse(wx.getStorageSync('mylocation'));
      latitude = mylocation.latitude;
      longitude = mylocation.longitude;
    } else {
      latitude = app.globalData.zone.lat;
      longitude = app.globalData.zone.lng;
    }
    http.post(api.default, {
      data: {
        action: 'getactivitydata',
        latitude: latitude,
        longitude: longitude,
        userid: userId,
        cityid: s_city,
        zoneid: zoneid,
        provinceid: s_province
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      this.setData({
        shop_list: data.shoplist,
        shop_list_top: data.shoplist.slice(0,3),
        shop_list_bot: data.shoplist.slice(3,5),
        // product_list:data.productlist,
        discountshoplist: data.discountshoplist,
        activedData: data.ms || 0
      })
    })
  },


  /**
   * 获取产品数据
   */
  getProductsInfo(cb, a = false) {
    let {
      goodsNavType,
      goodsListPage,
      goodsListPages,
      loaddone,
      abnor,
      userId,
      s_city,
      zoneid,
      s_province
    } = this.data;
    console.log("getProductsInfo---------s_province=", s_province)
    console.log("getProductsInfo---------s_city=", s_city)
    console.log("getProductsInfo---------zoneid=", zoneid)
    var latitude = 0,
      longitude = 0;
    var mylocation = null;
    if (wx.getStorageSync('mylocation') == "" && app.globalData.zone == null) {
      //wxApi.navigateTo("/pages/location/index");
      this.setData({
        islocation: true
      });
      return;
    } else if (wx.getStorageSync('mylocation') != "") {
      mylocation = JSON.parse(wx.getStorageSync('mylocation'));
      latitude = mylocation.latitude;
      longitude = mylocation.longitude;
    } else {
      latitude = app.globalData.zone.lat;
      longitude = app.globalData.zone.lng;
    }
    http.post(api.default, {
      data: {
        action: 'GetShopList',
        pagesize: 10,
        pageindex: goodsListPage,
        latitude: latitude,
        longitude: longitude,
        userid: userId,
        cityid: s_city,
        zoneid: zoneid,
        provinceid: s_province,
        pagetype: 'home'
      }
    }, a).then((res) => {
      const {
        data
      } = res.data;
      //是否加载完毕

      if (data.pages == 0)
        abnor = true;
      else
        abnor = false;
      if (goodsListPage == data.pages && !abnor) loaddone = true;
      this.setData({
        goodsListPages: data.pages,
        loaddone,
        abnor
      });
      console.log('getProductsInfo------------', goodsListPages)
      cb && cb(data);
    });
  },
  getRecShopList(cb, a = false) {
    let {
      rec_pageindex,
      rec_pages,
      rec_loaddone,
      userId,
      s_city,
      zoneid,
      s_province
    } = this.data;
    var mylocation = JSON.parse(wx.getStorageSync('mylocation'));
    http.post(api.default, {
      data: {
        action: 'GetRecShopList',
        pagesize: 20,
        pageindex: rec_pageindex,
        nocityid: s_city,
        nozoneid: zoneid,
        latitude: mylocation.latitude,
        longitude: mylocation.longitude,
        userid: userId,
        provinceid: s_province,
        pagetype: 'home'
      }
    }, a).then((res) => {
      const {
        data
      } = res.data;
      //是否加载完毕
      if (rec_pageindex == data.pages) rec_loaddone = true;
      this.setData({
        rec_pages: data.pages,
        rec_loaddone,
      });
      cb && cb(data);
    });
  },

  // handlehexiao(e){
  //   const {
  //     couponid
  //   } = e.currentTarget.dataset || e.target.dataset;
  //   wxApi.navigateTo(getPage.hexiao, {
  //       id: couponid
  //   });
  // },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },
  formatArea() {
    let {
      regionInfo,
      province
    } = this.data;
    province = [];
    regionInfo.forEach((item, index) => {
      province.push({
        text: item.name,
        value: item.id
      })
    });
    var cities = regionInfo[0].list;
    var city = [{
      text: "请选择",
      value: 0
    }];
    cities.forEach((c, i) => {
      city.push({
        text: c.name,
        value: c.id
      })
    });
    var zonelist = cities[0].list;
    var zones = [{
      text: "全部",
      value: 0
    }];
    zonelist.forEach((c, i) => {
      zones.push({
        text: c.name,
        value: c.id
      })
    });
    this.setData({
      province,
      s_province: province[0].value,
      cities: city,
      zonelist: zones,
      zoneid: 0
    });
  },
  province_change(e) {
    var id = e.detail;
    const {
      regionInfo
    } = this.data;
    let city = [{
      text: "请选择",
      value: 0
    }];
    var cityname = "";
    regionInfo.forEach((item, index) => {
      if (item.id == id) {
        cityname = item.name.replace('省', '').replace('市', '');
        var cities = item.list;
        cities.forEach((c, i) => {
          city.push({
            text: c.name,
            value: c.id
          })
        });
      }
    });
    this.setData({
      cities: city,
      s_city: 0,
      s_province: id,
      city: cityname
    });
    this.zoneSubmit();
    // this.getProductsInfo((res) => {
    //   this.setData({
    //     goodsList: res.list
    //   });
    //   if (this.data.loaddone || res.list.length == 0) {
    //     this.setData({
    //       rec_pageindex: 1,
    //       rec_pages: 0
    //     });
    //     this.getRecShopList((res1) => {
    //       this.setData({
    //         rec_list: res1.list,
    //         rec_loadmore: false,
    //       });
    //     });
    //   }
    // });
  },
  city_change(e) {
    var cityid = e.detail;
    console.log('city_change-------------', e.detail);
    let zone = [{
      text: "全部",
      value: 0
    }];
    var city = "";
    if (cityid == 0) {
      this.data.province.forEach((item, index) => {
        if (item.value == this.data.s_province)
          city = item.text.replace('省', '').replace('市', '');
      });
    }
    this.data.regionInfo.forEach((item, index) => {
      if (item.id == parseInt(this.data.s_province)) {
        var cities = item.list;
        cities.forEach((c, i) => {
          if (c.id == parseInt(cityid)) {
            var c_zone = c.list;
            city = c.name.replace('市', '');
            c_zone.forEach((z, j) => {
              zone.push({
                text: z.name,
                value: z.id
              });
            });
          }
        });
      }
    });
    this.setData({
      loadmore: false,
      s_city: cityid,
      zonelist: zone,
      city: city,
      zoneid: 0,
      goodsListPage: 1
    });
    this.zoneSubmit();
    // this.getProductsInfo((res) => {
    //   this.setData({
    //     goodsList: res.list
    //   });
    //   if (this.data.loaddone || res.list.length == 0) {
    //     this.setData({
    //       rec_pageindex: 1,
    //       rec_pages: 0
    //     });
    //     this.getRecShopList((res1) => {
    //       this.setData({
    //         rec_list: res1.list,
    //         rec_loadmore: false,
    //       });
    //     });
    //   }
    // });
  },
  zone_change(e) {
    var zoneid = e.detail;
    var city = this.data.city;
    console.log('zone_change-------', city);
    if (zoneid > 0) {
      this.data.zonelist.forEach((item, index) => {
        if (item.value == zoneid)
          city = item.text.replace('区', '').replace('县', '');
      });
    } else {
      this.data.cities.forEach((item, index) => {
        if (item.value == this.data.s_city)
          city = item.text.replace('市', '');
      });
    }
    this.setData({
      zoneid: zoneid,
      city: city,
      goodsListPage: 1
    });
    console.log('zone_change-------getProductsInfo');
    this.zoneSubmit();
    // this.getProductsInfo((res) => {
    //   this.setData({
    //     goodsList: res.list
    //   });
    //   if (this.data.loaddone || res.list.length == 0) {
    //     this.setData({
    //       rec_pageindex: 1,
    //       rec_pages: 0
    //     });
    //     this.getRecShopList((res1) => {
    //       this.setData({
    //         rec_list: res1.list,
    //         rec_loadmore: false,
    //       });
    //     });
    //   }
    // });
  },
  // zone_city_change(e) {
  //   var cityid = e.detail;
  //   this.setData({
  //     cityid: cityid
  //   });
  // },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options==', options)
    setTimeout(() => {
      this.setData({
        isbgtop:true
      })
    }, 10000);

    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //获取月份  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    this.setData({
      M
    })

    var _this = this;
    var first = 0;
    /**
     * 获取用户信息 
     */
    let logged, userId = '';
    app.getLogin().then((res) => {
      logged = res.code;
      userId = res.data.user.user_id;
      if(res.data.shop){
        this.setData({
          shop_id:res.data.shop.ShopId
        })
      }
    }).catch((res) => {
      logged = res;
    }).finally(() => {
      this.setData({
        logged,
        userId
      });
      if (options?.qudao) {
        let arroptions = options.qudao.split('$')
        console.log('arroptions============',arroptions)
        let qudao = arroptions[0];
        let click_id = arroptions[1];
        storage.set('qudao', qudao);
        storage.set('click_id', click_id);
        http.post(api.default, {

          data: {
            action: 'inithome',
            userid: userId,
            click_id: click_id,
            qudao
          }
        }, false).then(res => {
          console.log('1005===========res', res)
        })
      } else {
        storage.remove('qudao')
        storage.remove('click_id')
      }

      let parms = {
        action: 'apphome'
      }
      if(this.data.shop_id || this.data.shop_id===0){
        parms.shopid = this.data.shop_id
      }
      if(this.data.userId){
        parms.userid = this.data.userId
      }
      //第一部分数据加载
      http.get(api.default, {
        data: parms
      }, false).then((res) => {
        const {
          data
        } = res.data;
        console.log('data.popupads', data)
        this.setData({
          swiper: data.ban_list,
          notice: data.noticelist,
          loading: 1,
          wellcomepic: data.wellcomepic,
          showwellcome: data.showwellcome,
          HomeActivityTitle: data.HomeActivityTitle,
          homeshop: data.homeshop,
          botZtList: data.botZtList,
          designers: data.designers,
          popupads: data.popupads,
          v_count: data.v_count || 0
        });
        app.globalData.v_count = this.data.v_count;
        this.getTabBar().setData({
          v_count: app.globalData.v_count
        });
        if (this.data.popupads.length > 0) {
          this.setData({
            popupShow: true
          });
        }
        // var shoucang = wx.getStorageSync('shoucang');
        // if (shoucang == "") {
        //   this.setData({
        //     popupShowTip: true
        //   });
        //   storage.set('shoucang', 1);
        // }
        //倒计时
        //this.setCountDown(data.ms.EndTime);
      });
    })
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log('获取位置成功==========', res);
        storage.set('mylocation', res);
        console.log('获取位置成功==========', wx.getStorageSync('mylocation'));
        //获取设置城市id
        http.post(api.default, {
          data: {
            action: 'getzonebylocation',
            location: res.longitude + "," + res.latitude
          }
        }, false).then((res) => {
          const {
            data
          } = res.data;
          console.log('---------------------', res.data)
          if (data != null) {
            app.globalData.zoneid = data.region_id;
            app.globalData.zone = data;
            var temp = data.region_path.substring(1, data.region_path.length - 1).split(',');
            var s_province = parseInt(temp[0]);
            var s_city = 0;
            if (temp.length >= 2)
              s_city = parseInt(temp[1]);
            var zoneid = 0;
            if (temp.length == 3)
              zoneid = parseInt(temp[2]);
            _this.setData({
              city: app.globalData.zone.shortname
            });
            _this.getRegionInfo().then((res) => {
              //地区格式化
              //_this.formatArea();
              let province = [];
              let city1 = [{
                text: "请选择",
                value: 0
              }];
              console.log("位置---------------", res);
              var zones = [{
                text: "全部",
                value: 0
              }];
              res.forEach((item, index) => {
                province.push({
                  text: item.name,
                  value: item.id
                })
                if (item.id == s_province) {
                  var cities = item.list;
                  cities.forEach((c, i) => {
                    city1.push({
                      text: c.name,
                      value: c.id
                    })
                    if (s_city == c.id) {
                      var zonelist = c.list;
                      zonelist.forEach((z, j) => {
                        zones.push({
                          text: z.name,
                          value: z.id
                        })
                      });
                    }
                  });
                }
              });

              _this.setData({
                s_province: s_province,
                cities: city1,
                s_city: s_city,
                zonelist: zones,
                zoneid: zoneid
              });
              //请求列表
              console.log('onLoad获取位置内..................s_city=', _this.data.s_city)
              _this.getActivedList()
              _this.getProductsInfo((res) => {
                _this.setData({
                  goodsList: res.list,
                  loadmore: false,
                });
                if (_this.data.loaddone || _this.data.goodsListPages == 0) {
                  _this.getRecShopList((res1) => {
                    _this.setData({
                      rec_list: res1.list,
                      rec_loadmore: false,
                    });
                  });
                }
              });
            });

            console.log("globalData-------", app.globalData);

          }

        });


        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
      },
      fail(res) {
        console.log("位置fail-------", res);
        //请求列表
        _this.getActivedList()
        _this.getProductsInfo((res) => {
          console.log('onLoad位置fail..................getProductsInfo', res.list)
          _this.setData({
            goodsList: res.list,
            loadmore: false,
          });
          if (_this.data.loaddone || _this.data.goodsListPages == 0) {
            _this.getRecShopList((res1) => {
              _this.setData({
                rec_list: res1.list,
                rec_loadmore: false,
              });
            });
          }
        });
      },
      complete(res) {
        console.log("位置complete-------", res);
      }
    })
    this.getRegionInfo().then((res) => {
      //地区格式化
      this.formatArea();
    });
    //if (this.data.city == "")
    if (app.globalData.zone != null)
      this.setData({
        city: app.globalData.zone.shortname,
      })
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
  },

  godesignerdetail(e) {
    const data = e.currentTarget.dataset;
    if (data.id) {
      wxApi.navigateTo('/pages/companydetail/index', {
        id: data.id
      });
    }
  },

  /**
   * 关注店铺
   */
  followClick(event) {
    let {
      isfav,
      ShopId
    } = event.detail
    var {
      logged,
      userId,
    } = this.data;
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'fav_shop',
          userid: userId,
          shopid: ShopId,
        }
      }).then((res) => {
        let {
          errmsg,
          data
        } = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        // 前端显示跟新收藏状态
        let goodsArr = this.data.goodsList;
        goodsArr.forEach(item => {
          if (item.ShopId == ShopId) {
            item.isfav = data
          }
        })
        this.setData({
          goodsList: goodsArr
        })
      })
    } else {
      this.goLogin();
    }
  },




  /**
   * 页面滚动函数--监听页面滚动事件
   */
  onPageScroll(e) {
    var that = this;
    if (that.data.stkInitHeight == 0) this.getstkboxheight();
    if (that.data.navbarInitHeight == 0) this.getnavboxheight();

    wx.createSelectorQuery().select('.pannel_stb').boundingClientRect(function (rect) {
      if (rect && rect.top > 0) {
        // 列表盒子距顶部的高度
        var listInTop = parseInt(rect.top);
        var isSatisfy = (listInTop - that.data.stkInitHeight - that.data.navbarInitHeight) < 0 ? true : false;
        //为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
        if (that.data.isFixedTop === isSatisfy) {
          return false;
        }
        console.log('listInTop,stkInitHeight,navbarInitHeight', listInTop, that.data.stkInitHeight, that.data.navbarInitHeight)
        that.setData({
          isFixedTop: isSatisfy
        });
      }
    }).exec();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let that = this;
    setTimeout(() => {
      if (that.data.navbarInitHeight == 0) {
        this.getnavboxheight();
      }
      if (that.data.stkInitHeight == 0) {
        this.getstkboxheight();
      }
    }, 100)
  },

  // 获取navbar盒子高度
  getnavboxheight() {
    let that = this;
    wx.createSelectorQuery().select('.navbar').boundingClientRect(function (rect) {
      if (rect && rect.height > 0) {
        var navbarInitHeight = parseInt(rect.height);
        that.setData({
          navbarInitHeight: navbarInitHeight
        });
      }
    }).exec();
  },

  // 获取粘性盒子高度
  getstkboxheight() {
    let that = this;
    wx.createSelectorQuery().select('.panel_stk').boundingClientRect(function (rect) {
      if (rect && rect.height > 0) {
        var stkInitHeight = parseInt(rect.height);
        that.setData({
          stkInitHeight: stkInitHeight
        });
      }
    }).exec();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(options) {
    app.getLogin().then(res => {
      const {
        user
      } = res.data;
      this.setData({
        userId: user.user_id
      })
      this.getTabBar().setData({
        v_count: app.globalData.v_count
      });
      if (user.user_id > 0) {
        this.connectWebSocket();
        this.getunreadmsg();
        console.log('yonghuid', user.user_id)
      }
    })
    if (app.globalData.zone) {
      console.log('onShow----------', app.globalData.zone);
      this.getRegionInfo().then((res) => {
        //地区格式化
        //this.formatArea();
        let province = [];
        let city1 = [{
          text: "请选择",
          value: 0
        }];
        var zones = [{
          text: "全部",
          value: 0
        }];
        var temp = app.globalData.zone.region_path.substring(1, app.globalData.zone.region_path.length - 1).split(',');
        var s_province = parseInt(temp[0]);
        var s_city = 0;
        if (temp.length >= 2)
          s_city = parseInt(temp[1]);
        var zoneid = 0;
        if (temp.length == 3)
          zoneid = parseInt(temp[2]);
        res.forEach((item, index) => {
          province.push({
            text: item.name,
            value: item.id
          })
          if (item.id == s_province) {
            var cities = item.list;
            cities.forEach((c, i) => {
              city1.push({
                text: c.name,
                value: c.id
              })
              if (s_city == c.id) {
                var zonelist = c.list;
                zonelist.forEach((z, j) => {
                  zones.push({
                    text: z.name,
                    value: z.id
                  })
                });
              }
            });
          }
        });
        this.setData({
          province: province,
          s_province: s_province,
          cities: city1,
          s_city: s_city,
          zonelist: zones,
          zoneid: zoneid
        });
        this.getActivedList()
        //加载产品列表 
        if (this.data.goodsList.length == 0) {
          this.setData({
            goodsListPage: 1
          });
          this.getProductsInfo((res) => {
            console.log(res)
            this.setData({
              goodsList: res.list,
              loadmore: false,
            });
            if (this.data.loaddone || this.data.goodsListPages == 0) {
              this.setData({
                rec_pageindex: 1,
                rec_pages: 0
              });
              this.getRecShopList((res1) => {
                this.setData({
                  rec_list: res1.list,
                  rec_loadmore: false,
                });
              });
            }
          });
        }
      });
    }


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('onHide------------')
    wx.closeSocket()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('离开页面');
    wx.closeSocket()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showLoading({
      title: '加载中...',
    })
    this.setData({
      goodsListPage: 1
    })
    //加载产品列表
    this.getProductsInfo((res) => {
      console.log('onPullDownRefresh--------getProductsInfo', res)
      this.setData({
        goodsList: res.list,
        loadmore: false,
      });
      if (this.data.loaddone || this.data.goodsListPages == 0) {
        this.setData({
          rec_pageindex: 1,
          rec_pages: 0
        });
        this.getRecShopList((res1) => {
          this.setData({
            rec_list: res1.list,
            rec_loadmore: false,
          });
        });
      }
      wx.stopPullDownRefresh();
      wx.hideLoading();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('到底了')
    let {
      goodsListPage,
      goodsListPages,
      loadmore,
      rec_pageindex,
      rec_pages,
      rec_loadmore
    } = this.data;
    //未请求完且未在加载中
    console.log('goodsListPages=========', goodsListPages)
    console.log('goodsListPage=========', goodsListPage)
    console.log('loadmore=========', loadmore)
    if (goodsListPages > goodsListPage && !loadmore) {
      goodsListPage++;
      loadmore = false;

      //显示加载效果
      this.setData({
        goodsListPage,
        loadmore
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.getProductsInfo((res) => {
        console.log('底部---------getProductsInfo')
        let {
          goodsList
        } = this.data;
        loadmore = false;
        this.setData({
          loadmore,
          goodsList: goodsList.concat(res.list),
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    } else {
      console.log('底部--------rec_pages=', rec_pages);
      console.log('底部------rec_pageindex=', rec_pageindex);
      console.log('底部-------rec_loadmore=', rec_loadmore);
      if (rec_pageindex == 0)
        rec_loadmore = false;
      if (rec_pages >= rec_pageindex && !rec_loadmore) {
        rec_pageindex++;
        rec_loadmore = true;

        //显示加载效果
        this.setData({
          rec_pageindex,
          rec_loadmore
        });
        wx.showNavigationBarLoading();

        //请求数据
        this.getRecShopList((res) => {
          let {
            rec_list
          } = this.data;
          rec_loadmore = false;
          this.setData({
            rec_loadmore,
            rec_list: rec_list.concat(res.list),
          });
          //隐藏加载效果
          wx.hideNavigationBarLoading();
        })
      }
    }
  },
  // 获取未读消息数
  // getunreadmsg() {
  //   http.post(api.default, {
  //     data: {
  //       action: 'getunreadmsgcount',
  //       userid: this.data.userId
  //     }
  //   }, false).then(res => {
  //     console.log('未读消息=', res)
  //     console.log('this=', this)
  //     app.globalData.unReadMsg = res.data.data;
  //     if (typeof this.getTabBar === "function" && this.getTabBar()) {
  //       console.log('get===', this.getTabBar())
  //       this.getTabBar().setData({
  //         number: app.globalData.unReadMsg,
  //       });
  //     }
  //   })
  // },
  // 获取未读消息数
  getunreadmsg() {
    http.post(api.default, {
      data: {
        action: 'getmsgcount',
        userid: this.data.userId
      }
    }, false).then(res => {
      let {
        data
      } = res.data;
      let unReadMsg = data.msgcount + data.fw_notice + data.sys_notice
      app.globalData.unReadMsg = unReadMsg;
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        console.log('get===', this.getTabBar())
        this.getTabBar().setData({
          number: app.globalData.unReadMsg,
        });
      }
    })
  },

  //连接WebSocket服务器
  connectWebSocket: function () {
    var that = this
    wx.connectSocket({
      url: ChatConfig.CIM_URI,
      success: function (res) {
        console.log('WebSocket连接成功')
      },
      fail: function (res) {
        console.log('WebSocket连接失败:', res)
      }
    })
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开')
      that.setData({
        socketOpen: true
      })
      for (var i = 0; i < that.data.socketMsgQueue.length; i++) {
        that.sendSocketMessage(that.data.socketMsgQueue[i])
      }
      that.setData({
        socketMsgQueue: []
      })
      that.innerOnConnectFinished();
    })
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败:', res)
    })
    wx.onSocketClose(function (res) {
      console.log('离开页面--------');
      console.log('WebSocket连接已关闭:', res)
      that.setData({
        socketOpen: false
      });
      // that.innerOnConnectionClosed(res);
    })
    wx.onSocketMessage(function (res) {
      console.log('接收到服务器发送的数据:', res.data)
      that.innerOnMessageReceived(res);
      // var messages = that.data.messages
      // messages.push(res.data)
      // that.setData({
      //   messages: messages,
      //   scrollIntoView: 'message-' + messages.length
      // })
    })
  },
  innerOnConnectFinished: function () {
    let account = "";
    if (account === '' || account === undefined) {
      this.onConnectFinished();
    } else {
      this.bindAccount(account);
    }
  },
  onConnectFinished: function () {
    //获取当前登录用户
    app.getLogin().then((res) => {
      console.log(res);
      this.bind(res.data.user.user_id);
    })
  },
  bind: function (account) {
    storage.set('account', account);
    let deviceId = ""; //storage.get('deviceId');
    if (deviceId === '' || deviceId === undefined) {
      deviceId = this.generateUUID();
      storage.set('deviceId', deviceId)
    }
    let browser = "微信小程序";
    let body = {};
    body.key = ChatConfig.KEY_CLIENT_BIND;
    body.timestamp = new Date().getTime();
    body.data = {};
    body.data.uid = account;
    body.data.channel = ChatConfig.APP_CHANNEL;
    body.data.appVersion = ChatConfig.APP_VERSION;
    body.data.packageName = ChatConfig.APP_PACKAGE;
    body.data.deviceId = deviceId;
    body.data.deviceName = browser;
    console.log(body);
    this.sendRequest(body);
  },
  sendRequest: function (body) {
    let data = {};
    data.type = ChatConfig.SENT_BODY;
    data.content = JSON.stringify(body);
    this.sendSocketMessage(JSON.stringify(data));
  },
  innerOnMessageReceived(e) {
    console.log(e)
    let data = JSON.parse(e.data);
    let type = data.type;
    let body = data.content;
    if (type === ChatConfig.PING) {
      this.pong();
      return;
    }

    if (type === ChatConfig.MESSAGE) {
      let message = JSON.parse(body);
      this.onInterceptMessageReceived(message);
      return;
    }

    if (type === ChatConfig.REPLY_BODY) {
      let reply = JSON.parse(body);
      /*
       * 判断是否是握手鉴权失败
       * 终止后续自动重连
       */
      if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
        this.setData({
          manualStop: true
        });
      }
      this.onReplyReceived(reply);
    }
  },
  pong: function () {
    let data = {};
    data.type = ChatConfig.PONG;
    data.content = ChatConfig.PONG_BODY;
    this.sendSocketMessage(JSON.stringify(data));
  },
  onInterceptMessageReceived(message) {
    /*
     *被强制下线之后，不再继续连接服务端
     */
    if (message.action === ChatConfig.ACTION_999) {
      this.setData({
        manualStop: true
      });
    }
    app.globalData.unReadMsg++;
    console.log('"list[3].number":app.globalData.unReadMsg++++', app.globalData.unReadMsg)
    this.getTabBar().setData({
      number: app.globalData.unReadMsg,
    });
    console.log('++++', app.globalData.unReadMsg)
  },
  onReplyReceived(reply) {
    console.log(reply);
    if (reply.key === ChatConfig.KEY_CLIENT_BIND && reply.code === ChatConfig.CODE_OK) {
      console.log('登录成功');
      // hideProcess();

      // $('#LoginDialog').fadeOut();

      // $('#MessageDialog').fadeIn();
      // $('#MessageDialog').addClass("in");
      // $("#current_account").text($('#account').val());

    }

    /**
     * 链接鉴权失败
     */
    if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
      //hideProcess();
      console.log("鉴权失败");
    }
  },

  innerOnConnectionClosed: function (e) {
    var _this = this;
    if (!_this.data.manualStop) {
      let time = Math.floor(Math.random() * (30 - 15 + 1) + 15);
      setTimeout(function () {
        console.log("Socket重新连接")
        _this.connectWebSocket(); //重新连接
      }, time);
    }
  },
  generateUUID() {
    let d = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid.replace(/-/g, '');
  },
  // 发送WebSocket消息
  sendSocketMessage: function (message) {
    if (this.data.socketOpen) {
      wx.sendSocketMessage({
        data: message
      })
    } else {
      this.data.socketMsgQueue.push(message)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.userId > 0) {
      pageshare += "?pid=" + this.data.userId;
    }
    return {
      title: ``,
      imageUrl: '',
      path: pageshare,
      success: function (res) {
        console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          console.log("分享失败");
        }
      }
    }
  }
})